

#include <string.h>
#include <include/frame_process.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <zlib.h>



/*环形缓冲区start*/
void buffer_init(struct buffer *buf) 
{
    pthread_mutex_init(&buf->mutex, NULL);
    pthread_cond_init(&buf->not_empty, NULL);//初始化条件变量
    pthread_cond_init(&buf->not_full, NULL);
    buf->read_pos = buf->write_pos = buf->size = 0;
}


void buffer_put(struct buffer * g_buf, Frame_DATA_p frame) 
{

    
    pthread_mutex_lock(&g_buf->mutex);


    //当传入的数组最满时，进程阻塞等待不满的信号
     while(g_buf->size == BUFFER_SIZE)
    {

                 pthread_cond_wait(&g_buf->not_full, &g_buf->mutex);
        //左移
//        for(int i=0;i<BUFFER_SIZE-1;i++)
//        {
//             g_buf->Frame_DATA[i] =  g_buf->Frame_DATA[i+1];
//        }
//        g_buf->Frame_DATA[BUFFER_SIZE-1] = *frame;
//       pthread_mutex_unlock(&g_buf->mutex);
//        return;



    }
    //将value写入到数组当前写入的位置中
    g_buf->Frame_DATA[g_buf->write_pos] = *frame; //printf("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
    //令当前位置加一
    g_buf->write_pos = (g_buf->write_pos + 1) % BUFFER_SIZE; //printf("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
    //已写的长度加一
    g_buf->size++;
    //上述执行完毕，表示此数组不是空的，发送信号
    pthread_cond_signal(&g_buf->not_empty);
    pthread_mutex_unlock(&g_buf->mutex);
}

Frame_DATA_p buffer_get(struct buffer *g_buf)
 {
    pthread_mutex_lock(&g_buf->mutex);

    //当传入的数组没有数据时，等待不是空的信号
    while (g_buf->size == 0)
    {
 //                pthread_cond_wait(&g_buf->not_full, &g_buf->mutex);


            pthread_mutex_unlock(&g_buf->mutex);
            return NULL;

    }

    //将此时正在读的位置的值读出
    Frame_DATA_p value = &g_buf->Frame_DATA[g_buf->read_pos];
    //此时读的位置加一
    g_buf->read_pos = (g_buf->read_pos + 1) % BUFFER_SIZE;
    //读取到数据后，整体数据减小
    g_buf->size--;
    //上述执行完毕，表示此数组不是满的，发送信号
    pthread_cond_signal(&g_buf->not_full);
    pthread_mutex_unlock(&g_buf->mutex);
    return value;
}

/*环形缓冲区end*/



//destroy all 

void pthread_destroy(struct buffer *g_buf)
{

    pthread_mutex_destroy(&g_buf->mutex);
    pthread_cond_destroy(&g_buf->not_empty);
    pthread_cond_destroy(&g_buf->not_full);


}









